package com.jzlin.funhub.framework.core.db;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jzlin.funhub.framework.common.consts.BaseConst;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 基础实体字段填充 如更新时间、更新人.
 *
 * @author linjz
 * @since 2025/5/23
 */
@Component
public class EntityBaseMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        long userId = getUserId();
        this.strictInsertFill(metaObject, "createBy", Long.class, userId);
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        long userId = getUserId();
        this.strictUpdateFill(metaObject, "updateBy", Long.class, userId);
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
    }

    private static long getUserId() {
        long userId;
        if (StpUtil.isLogin()) {
            userId = StpUtil.getLoginIdAsLong();
        } else {
            userId = BaseConst.SYSTEM_USER_ID;
        }
        return userId;
    }
}
